<template>
  <div class="addProtocol">
    <el-drawer
      :visible.sync="show"
      :title="title"
      width="650px"
      class="upload-dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :direction="direction"
      :before-close="handleClose"
      @close="close()"
    >
      <el-form ref="model" :model="model" :rules="rules" label-width="90px">
        <el-form-item label="配置名称:" prop="name">
          <el-input v-model="model.name" placeholder="配置名称" class="input-width" />
        </el-form-item>
        <el-form-item label="配置内容:" prop="configDetail">
          <codemirror
            ref="myCm"
            v-model="model.configDetail"
            class="code"
            style="padding-right:40px;"
            :options="cmOptions"
            @changes="onCmCodeChanges"
            @blur="onCmBlur"
            @keydown.native="onKeyDown"
            @mousedown.native="onMouseDown"
            @paste.native="OnPaste"
          />
        </el-form-item>
        <el-form-item label="配置说明:" prop="des">
          <el-input
            v-model="model.des"
            type="textarea"
            :rows="3"
            placeholder="请输入描述信息"
            class="input-width"
            maxlength="255"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div style="display:flex;justify-content:flex-end;margin-bottom:20px;margin-right:20px;">
        <el-button size="small" @click="close()">取 消</el-button>
        <el-button size="small" type="primary" @click="submit">确 认</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
  import {remoteConfigPut} from "@/api/device";

  import {codemirror} from "vue-codemirror";
  require("script-loader!jsonlint")
  import 'codemirror/lib/codemirror.css'
  import 'codemirror/keymap/sublime' //sublime编辑器效果
  import "codemirror/theme/dracula.css"// 配置里面也需要theme设置为monokai
  import "codemirror/mode/vue/vue.js" // 配置里面也需要mode设置为vue
  import "codemirror/addon/selection/active-line.js" //光标行背景高亮，配置里面也需要styleActiveLine设置为true
  import "codemirror/mode/javascript/javascript.js"
  import "codemirror/mode/xml/xml.js"
  import "codemirror/mode/htmlmixed/htmlmixed.js"
  import "codemirror/mode/css/css.js"
  import "codemirror/mode/yaml/yaml.js"
  import "codemirror/mode/sql/sql.js"
  import "codemirror/mode/python/python.js"
  import "codemirror/mode/markdown/markdown.js"
  import "codemirror/addon/hint/show-hint.css"
  import "codemirror/addon/hint/show-hint.js"
  import "codemirror/addon/hint/javascript-hint.js"
  import "codemirror/addon/hint/xml-hint.js"
  import "codemirror/addon/hint/css-hint.js"
  import "codemirror/addon/hint/html-hint.js"
  import "codemirror/addon/hint/sql-hint.js"
  import "codemirror/addon/hint/anyword-hint.js"
  import "codemirror/addon/lint/lint.css"
  import "codemirror/addon/lint/lint.js"
  import "codemirror/addon/lint/json-lint"
  import "codemirror/addon/hint/show-hint.js"
  import "codemirror/addon/hint/anyword-hint.js"
  import "codemirror/addon/lint/javascript-lint.js"
  import "codemirror/addon/fold/foldcode.js"
  import "codemirror/addon/fold/foldgutter.js"
  import "codemirror/addon/fold/foldgutter.css"
  import "codemirror/addon/fold/brace-fold.js"
  import "codemirror/addon/fold/xml-fold.js"
  import "codemirror/addon/fold/comment-fold.js"
  import "codemirror/addon/fold/markdown-fold.js"
  import "codemirror/addon/fold/indent-fold.js"
  import "codemirror/addon/edit/closebrackets.js"
  import "codemirror/addon/edit/closetag.js"
  import "codemirror/addon/edit/matchtags.js"
  import "codemirror/addon/edit/matchbrackets.js"
  import "codemirror/addon/search/jump-to-line.js"
  import "codemirror/addon/dialog/dialog.js"
  import "codemirror/addon/dialog/dialog.css"
  import "codemirror/addon/search/searchcursor.js"
  import "codemirror/addon/search/search.js"
  import "codemirror/addon/display/autorefresh.js"
  import "codemirror/addon/selection/mark-selection.js"
  import "codemirror/addon/search/match-highlighter.js"
  export default {
    name: "AddConfig",
    components: {
      codemirror
    },
    props: {
      insertVisible: Boolean,
      updateData: {
        type: Object,
        default: function () {
          return {}
        }
      }
    },
    data() {
      return {
        title: '新增配置',
        model: {
          configDetail:'{}'
        },
        show: false,
        delId: '',
        rules: {
          name: [
            {required: true, message: '配置名称是必填项'},
            { min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur' }
          ],
          configDetail:[
            {required: true, message: '输入配置内容'},
            { max: 10240, message: '长度不超过10240个字符', trigger: 'blur' }
          ]
        },
        protocolLists: [],
        config: [],
        cmOptions: {
          theme: 'default',  // 主题
          mode: 'application/json',  // 代码格式
          tabSize: 4,  // tab的空格个数
          indentUnit: 2,  // 一个块（编辑语言中的含义）应缩进多少个空格
          autocorrect: true,  // 自动更正
          spellcheck: true,  // 拼写检查
          lint: true,  // 检查格式
          lineNumbers: true,  //是否显示行数
          lineWrapping: true, //是否自动换行
          styleActiveLine: true,  //line选择是是否高亮
          keyMap: 'sublime',  // sublime编辑器效果
          matchBrackets: true,  //括号匹配
          autoCloseBrackets: true,  // 在键入时将自动关闭括号和引号
          matchTags: {bothTags: true},  // 将突出显示光标周围的标签
          foldGutter: true,  // 可将对象折叠，与下面的gutters一起使用
          gutters: [
            "CodeMirror-lint-markers",
            "CodeMirror-linenumbers",
            "CodeMirror-foldgutter"
          ],
          highlightSelectionMatches: {
            minChars: 2,
            style: "matchhighlight",
            showToken: true
          }
        },
        direction: 'rtl',
      }
    },
    watch: {
      insertVisible(val) {
        if (val) {
          this.show = val
        }
      },
      updateData(val) {
        console.log(val,'新增配置')
        if (val !== null) {
          this.title = '编辑配置'
          this.model = val
        }else{
          this.title = '新增配置'
          this.model= {}
        }
      }
    },
    methods: {
      submit() {
        this.$refs.model.validate((valid) => {
          if (valid) {
            return remoteConfigPut(this.model).then((res) => {
              if (res.code === 200010) {
                this.$notify({
                  title: '提示',
                  type: 'success',
                  message: '保存成功',
                  duration: 3000
                });
                // this.$message.success("保存成功")
                this.model= {}
                this.$emit('submitClose')
                this.show = false
                this.$refs['model'].resetFields();
              } else {
                this.$notify({
                  title: '提示',
                  type: 'warning',
                  message: res.message,
                  duration: 3000
                });
                // this.$message.warning(res.message)
              }
            }).catch(err => {
              console.log(err)
            })
          } else {
            return false
          }
        })
      },
      handleCancel() {
        this.$emit('modalClose')
      },
      handleClose(done){
        this.$emit('modalClose')
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      close() {
        if(this.show){
          this.$confirm('确认关闭吗?', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          }).then(() => {
            this.$refs['model'].resetFields();
            this.config=[]
            this.model = {}
            this.show = false
            this.$emit('modalClose')
          })
        }else{
          this.$refs['model'].resetFields();
          this.config=[]
          this.model = {}
          this.show = false
          this.$emit('modalClose')
        }
      },
      // 删除左右两端的空格
      trim(str) {
        return str.replace(/(^\s*)|(\s*$)/g, '')
      },
      channelInputLimit(e) {
        let key = e.key
        // 不允许输入'e'和'.'
        if (key === 'e' || key === '.') {
          e.returnValue = false
          return false
        }
        return true
      },
      onCmCodeChanges(cm, changes) {
        this.model.configDetail = cm.getValue();
        this.resetLint();
      },
      resetLint() {
        if (!this.$refs.myCm.codemirror.getValue()) {
          this.$nextTick(() => {
            this.$refs.myCm.codemirror.setOption("lint", false);
          });
          return;
        }
        this.$refs.myCm.codemirror.setOption("lint", false);
        this.$nextTick(() => {
          this.$refs.myCm.codemirror.setOption("lint", true);
        });
      },
      // 失去焦点时处理函数
      onCmBlur(cm, event) {
        try {
          let editorValue = cm.getValue();
          if (this.cmOptions.mode === "application/json" && editorValue) {
            if (!this.enableAutoFormatJson) {
              return;
            }
            this.model.configDetail = this.formatStrInJson(editorValue);
          }
        } catch (e) {
          // 啥也不做
        }
      },
      // 按下键盘事件处理函数
      onKeyDown(event) {
        const keyCode = event.keyCode || event.which || event.charCode;
        const keyCombination =
          event.ctrlKey || event.altKey || event.metaKey;
        if (!keyCombination && keyCode > 64 && keyCode < 123) {
          this.$refs.myCm.codemirror.showHint({completeSingle: false});
        }
      },
      // 按下鼠标时事件处理函数
      onMouseDown(event) {
        this.$refs.myCm.codemirror.closeHint();
      },
      // 黏贴事件处理函数
      OnPaste(event) {
        if (this.cmOptions.mode === "application/json") {
          try {
            this.model.configDetail = this.formatStrInJson(this.model.configDetail);
          } catch (e) {
            // 啥都不做
          }
        }
      },
      // 格式化字符串为json格式字符串
      formatStrInJson(strValue) {
        return JSON.stringify(
          JSON.parse(strValue),
          null,
          2
        );
      },
    }
  }
</script>

<style lang="scss" scoped>
.input-width {
  width: 90%;
}

.input-width1 {
  width: 310px;
}
/deep/.el-form-item__content {
  line-height: 20px;
  position: relative;
  font-size: 14px;
}

/deep/ input::-webkit-outer-spin-button,
/deep/ input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}

/deep/ input[type='number'] {
  -moz-appearance: textfield !important;
}

.addProtocol {
  .upload-dialog {
    /deep/ .el-dialog__body {
      padding: 30px 0px;

      ::-webkit-scrollbar {
        width: 5px;
        height: 1px;
      }

      ::-webkit-scrollbar-thumb { //滑块部分
        border-radius: 5px;
        background-color: rgb(232, 226, 236);
      }

      ::-webkit-scrollbar-track { //轨道部分
        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: #ededed;
        border-radius: 5px;
      }
    }

    .el-dialog {
      .el-dialog__body {
        padding: 30px 0px
      }

      .el-form {
        padding-right: 20px;
        padding-left: 20px;
      }
    }
  }
}
/deep/.el-textarea__inner{
  border-color: #91d5ff !important;
}
</style>
